<template>
  <div class="timesale-item-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑' : '查看' }}限时抢购活动</span>
        <el-button 
          v-if="isEdit && !isView" 
          style="float: right; margin-top: -5px" 
          type="primary" 
          @click="submitForm">
          提交
        </el-button>
        <el-button 
          v-else 
          style="float: right; margin-top: -5px" 
          type="primary" 
          @click="$router.push({ path: '/timesale' })">
          返回
        </el-button>
      </div>
      <el-form :model="formData" label-width="120px">
        <el-form-item label="活动名称" :disabled="isView">
          <el-input v-model="formData.saleName" :disabled="isView" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" :disabled="isView">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :disabled="isView">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="isView">
          </el-date-picker>
        </el-form-item>
        <!-- 限购数量，默认为 1 -->
        <el-form-item label="限购数量" :disabled="isView">
          <el-input v-model="formData.maxPurchase" :disabled="isView" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-tag :type="getStatusType(formData.saleStatus)">{{ formData.statusName }}</el-tag>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>活动商品</span>
        <el-button 
          v-if="isEdit && !isView" 
          style="float: right; margin-top: -5px; margin-left: 20px;" 
          type="danger" 
          @click="handleBatchRemoveGoods">
          批量移除
        </el-button>
        <el-button 
          v-if="isEdit && !isView" 
          style="float: right; margin-top: -5px" 
          type="primary" 
          @click="handleAddGoods">
          添加商品
        </el-button>
      </div>
      <el-table :data="formData.goodsList" stripe border fit highlight-current-row max-height="220" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" v-if="isEdit && !isView"></el-table-column>
        <el-table-column prop="productId" label="商品ID"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column label="原价">
          <template slot-scope="scope">
            {{ scope.row.price }} 元
          </template>
        </el-table-column>
        <el-table-column label="促销价" :disabled="isView">
          <template slot-scope="scope">
            <el-input 
              v-if="isEdit && !isView" 
              v-model="scope.row.flashPrice" 
              size="small">
            </el-input>
            <span v-else>{{ scope.row.flashPrice }} 元</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <!-- 活动库存 -->
        <el-table-column label="活动库存">
          <template slot-scope="scope">
            <el-input 
              v-if="isEdit && !isView" 
              v-model="scope.row.flashStock" 
              size="small">
            </el-input>
            <span v-else>{{ scope.row.flashStock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="isEdit && !isView">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleRemoveGoods(scope.$index)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="formData.goodsList && formData.goodsList.length > 0"
        @size-change="handleGoodsSizeChange"
        @current-change="handleGoodsCurrentChange"
        :current-page="pageParam.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加商品弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="选择商品">
      <el-form :inline="true" :model="addGoods" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input v-model="addGoods.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchAvailableGoods">查询</el-button>
          <el-button @click="resetGoodsQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table 
        ref="multipleTable"
        :data="availableGoodsList" 
        stripe 
        border 
        fit 
        highlight-current-row
        @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="商品ID"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="价格">
          <template slot-scope="scope">
            {{ scope.row.price }} 元
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template>
            <el-tag type="success">已上架</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddGoods">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        saleId: null,
        saleName: '',
        startTime: '',
        endTime: '',
        saleStatus: 1,
        statusName: '未开始',
        maxPurchase: 1,
        goodsList: []
      },
      dialogVisible: false,
      availableGoodsList: [],
      selectedGoods: [],
      addGoods: {
        name: ''
      },
      pageParam: {
        pageNum: 1,
        pageSize: 10,
        param: {}
      },
      total: 0,
      isEdit: true,
      isView: false
    }
  },
  props: {
    mode: {
      type: String,
      required: true
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    initFormData() {
      const route = this.$route
      if (route.name === 'timesaleItem-create') {
        // 新增活动
        this.isEdit = true
        this.isView = false
        this.resetFormData()
      } else {
        // 编辑或查看活动
        this.formData.saleId = route.query.saleId
        this.formData.saleStatus = route.query.saleStatus
        // 获取活动详情
        this.$axios.get(`api/timesale/queryTimeSaleDetail/${this.formData.saleId}`).then(resp => {
          if (resp.data.code === 200) {
            this.formData = resp.data.data
            this.total = this.formData.goodsList.length
          } else {
            this.$message.error('获取活动详情失败，错误码：' + resp.data.code)
          }
        }).catch(err => {
          this.$message.error('获取活动详情失败，错误信息：' + err.message)
        })
        // 判断是否为查看模式（已结束或已取消的活动）
        this.isView = this.formData.saleStatus === 2 || this.formData.saleStatus === 3 || this.formData.saleStatus === 4
        this.isEdit = !this.isView
      }
    },
    // 重置表单数据
    resetFormData() {
      this.formData = {
        saleId: null,
        saleName: '',
        startTime: '',
        endTime: '',
        saleStatus: 1,
        statusName: '未开始',
        maxPurchase: 1,
        goodsList: []
      }
    },
    getStatusType(status) {
      const typeMap = {
        1: 'default',
        2: 'success',
        3: 'info',
        4: 'danger'
      }
      return typeMap[status] || 'default'
    },
    handleAddGoods() {
      this.dialogVisible = true
      this.fetchAvailableGoods()
    },
    fetchAvailableGoods() {
      // 获取可用商品列表
      this.$axios.get(`api/timesale/queryAvailableGoods?name=` + this.addGoods.name).then(resp => {
        if (resp.data.code === 200) {
          this.availableGoodsList = resp.data.data
        } else {
          this.$message.error('获取商品列表失败，错误码：' + resp.data.code)
        }
      }).catch(err => {
        this.$message.error('获取商品列表失败，错误信息：' + err.message)
      })
    },
    // 处理商品选择变化
    handleGoodsSelectionChange(val) {
      this.selectedGoods = val
    },
    // 确认添加商品
    confirmAddGoods() {
      if (this.selectedGoods.length === 0) {
        this.$message.error('请选择要添加的商品')
        return
      }
      
      // 将选择的商品添加到活动商品列表
      const newGoods = this.selectedGoods.map(good => {
        return {
          productId: good.id,
          goodsName: good.name,
          price: good.price,
          flashPrice: good.price, // 默认促销价等于原价
          stock: good.stock,
          flashStock: good.stock // 默认活动库存等于商品库存
        }
      })
      
      this.formData.goodsList = [...this.formData.goodsList, ...newGoods]
      this.total = this.formData.goodsList.length
      
      this.dialogVisible = false
      this.$message.success('添加商品成功')
    },
    handleRemoveGoods(index) {
      this.$confirm('确定要移除这个商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.goodsList.splice(index, 1)
        this.total = this.formData.goodsList.length
        this.$message({
          type: 'success',
          message: '移除商品成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleBatchRemoveGoods() {
      if (this.selectedGoods.length === 0) {
        this.$message.error('请选择要移除的商品')
        return
      }

      this.$confirm('确定要移除选中的商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = this.selectedGoods.map(good => good.productId)
        this.formData.goodsList = this.formData.goodsList.filter(
          good => !selectedIds.includes(good.productId)
        )
        this.total = this.formData.goodsList.length
        this.selectedGoods = []
        this.$message({
          type: 'success',
          message: '批量移除商品成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    resetGoodsQuery() {
      this.addGoods.name = ''
      this.fetchAvailableGoods()
    },
    handleGoodsSizeChange(val) {
      this.pageParam.pageSize = val
      this.fetchAvailableGoods()
    },
    handleGoodsCurrentChange(val) {
      this.pageParam.pageNum = val
      this.fetchAvailableGoods()
    },
    submitForm() {
      // 表单验证
      if (!this.formData.saleName) {
        this.$message.error('请输入活动名称')
        return
      }
      
      if (!this.formData.startTime || !this.formData.endTime) {
        this.$message.error('请选择活动开始时间和结束时间')
        return
      }

      if (new Date(this.formData.startTime) < new Date()) {
        this.$message.error('活动开始时间不能早于当前时间')
        return
      }

      if (this.formData.startTime === this.formData.endTime) {
        this.$message.error('活动开始时间和结束时间不能相同')
        return
      }
      
      if (new Date(this.formData.startTime) >= new Date(this.formData.endTime)) {
        this.$message.error('活动开始时间必须早于结束时间')
        return
      }
      
      if (!this.formData.goodsList || this.formData.goodsList.length === 0) {
        this.$message.error('请添加活动商品')
        return
      }
      
      // 提交数据新增或编辑活动
      const apiUrl = this.mode === 'view' ? 'api/timesale/updateTimeSale' : 'api/timesale/addTimeSale'
      this.$axios.post(apiUrl, this.formData).then(resp => {
        if (resp.data.code === 200) {
          this.$message.success('活动提交成功')
          this.$router.push({ path: '/timesale' })
        } else {
          this.$message.error('活动提交失败，错误码：' + resp.data.code)
        }
      }).catch(err => {
        this.$message.error('活动提交失败，错误信息：' + err.message)
      })
    }
  }
}
</script>

<style scoped>
</style>  